import store from "@/store";
import { wechatMpCardUrl } from "@/api/wechat";
import { cardTempInfo, cardInfo, voucherClerk } from "@/api/alipay/coupon";
import http from "@/common/http.js";

export default {
  clerkAliCoupon(res) {
    if (res.result) {
      let ovcoupon = res.result;
      let ovpre = ovcoupon.substr(0, 2);
      if (ovpre !== "ov") {
        return 1;
      }
      uni.navigateTo({
        url: "/user/clerk/voucher?ov=" + ovcoupon
      });
      return 0;
    } else {
      uni.showModal({
        content: "扫码失败。"
      });
    }
    return 0;
  },

  //保留当前页面，跳转到应用内的某个页面
  toUrl(url, type) {
    // #ifdef MP-TOUTIAO
    if (type == "switchtab") type = "redirectTo";
    // #endif

    if (type == "navigate") {
      uni.navigateTo({
        url
      });
    } else if (type == "switchtab") {
      if (url.indexOf("/pages/cat/cat") !== -1) {
        let params = this.oneValues(url);
        store.commit("setGoCatId", params.cat_id || "");
      }
      // #ifdef MP-ALIPAY
      my.reLaunch({
        url
      });
      // #endif
      // #ifndef MP-ALIPAY
      uni.switchTab({
        url
      });
      // #endif
      return;
    } else if (type == "tel") {
      var vars = url.split("?");
      if (vars.length > 1) {
        var query = vars[1].split("&");
        for (var i = 0; i < query.length; i++) {
          var pair = query[i].split("=");
          if (pair[0] == "tel") {
            this.makePhoneCall(pair[1]);
          }
        }
      }
      return;
    } else if (type == "wxapp") {
      let index = url.lastIndexOf("?");
      let newParams = "";
      if (index != -1) newParams = url.slice(index);

      var vars = url.split("?");
      if (vars.length > 1) {
        var query = vars[1].split("&");
        var api = {
          appid: "",
          path: ""
        };
        for (var i = 0; i < query.length; i++) {
          var pair = query[i].split("=");
          if (pair[0] == "appid") {
            api.appid = pair[1];
          }
          if (pair[0] == "path") {
            api.path = pair[1];
          }
        }

        uni.navigateToMiniProgram({
          appId: api.appid,
          path: api.path + newParams
        });
      }
      return;
    } else if (type == "reLaunch") {
      uni.reLaunch({
        url
      });
      return;
    } else if (type == "redirectTo") {
      uni.redirectTo({
        url: url
      });
      return;
    } else if (type == "clerk") {
      uni.scanCode({
        success: (res) => {
          // #ifdef MP-ALIPAY || H5
          if (res.qrCode) {
            uni.navigateTo({
              url: "/" + res.qrCode
            });
            return;
          }
          // #endif
          // #ifndef MP-ALIPAY
          if (res.path) {
            uni.navigateTo({
              url: "/" + res.path
            });
            return;
          }
          // #endif

          let cACoupon = this.clerkAliCoupon(res);
          if (!cACoupon) {
            return;
          }
        }
      });
      return;
    } else if (type == "weChatCart") {
      // #ifdef MP-WEIXIN
      wechatMpCardUrl().then((res) => {
        let { encrypt_card_id, biz } = res;

        wx.navigateToMiniProgram({
          appId: "wxeb490c6f9b154ef9",
          extraData: {
            encrypt_card_id: decodeURIComponent(encrypt_card_id),
            outer_str: "1",
            biz: decodeURIComponent(biz)
          } // 包括encrypt_card_id outer_str biz三个字段，须从step3中获得的链接中获取参数
        });
      });
      // #endif
      // #ifndef MP-WEIXIN
      this.showModal("提示", "当前环境不支持此次操作!", false, () => {
        this.goBack();
      });
      // #endif
      return;
    } else if (type == "alipayCard") {
      // #ifdef MP-ALIPAY
      cardInfo({}, true).then((res) => {
        if (res.card && res.apires.data && res.apires.data.schema_url) {
          my.openCardDetail({
            passId: res.apires.data.pass_id,
            success: (res) => {}
          });
        } else {
          cardTempInfo({}, true).then((res) => {
            const plugin = requirePlugin("cardPlugin");
            if (res.code)
              return uni.showToast({
                title: res.msg,
                icon: "none",
                duration: 2000
              });
            let { template_id: templateId } = res.data,
              cardParams = {
                templateId,
                templateAppId: res.apires.mini
                  ? res.apires.mini.auth_app_id
                  : ""
                // pageType: "full",
              };
            if (res.data.join_benefit_id) {
              cardParams.joinBenefitType = "VOUCHER_MRCH";
              cardParams.joinBenefitId = res.data.join_benefit_id;
            }
            plugin.openCard({
              cardParams,
              callback(res) {}
            });
          });
        }
      });
      // #endif
      // #ifndef MP-ALIPAY
      this.showModal("提示", "当前环境不支持此次操作!", false, () => {
        this.goBack();
      });
      // #endif
    } else if (type == "videoShopLive" || type == "videoShop") {
      // #ifdef MP-WEIXIN
      let { finder_id } = this.oneValues(url);
      if (finder_id) {
        let SDKVersion = uni.getStorageSync("SDKVersion");
        switch (type) {
          case "videoShop":
            if (this.compare(SDKVersion, "2.21.2")) {
              wx.openChannelsUserProfile({
                finderUserName: finder_id
              });
            } else {
              this.toast("当前版本不支持!");
            }
            break;

          case "videoShopLive":
            if (this.compare(SDKVersion, "2.15.0")) {
              wx.getChannelsLiveInfo({
                finderUserName: finder_id,
                success: (res) => {
                  let { status, feedId, nonceId } = res;
                  if (status === 2) {
                    wx.openChannelsLive({
                      finderUserName: finder_id,
                      feedId,
                      nonceId
                    });
                    return;
                  }

                  this.toast("直播已结束!");
                }
              });
            } else {
              this.toast("当前版本不支持!");
            }
            break;
        }
        return;
      }

      this.toast("参数不存在!");
      // #endif
      // #ifndef MP-WEIXIN
      this.toast("当前环境不支持此次操作!");
      // #endif

      return;
    } else if (type == "web") {
      if (url) {
        this.toUrl(`/other/webview/webview?src=${url}`);
      } else {
        this.toast("当前未设置外链链接!");
      }
    } else {
      uni.navigateTo({
        url
      });
    }
  },
  //购物车自营商品判断全选
  ischecked(item) {
    var check = true;
    if (item.length == 0) {
      check = false;
    } else {
      for (var i = 0; i < item.length; i++) {
        if (item[i].is_checked == false) {
          check = false;
          break;
        }
      }
    }
    return check;
  },
  //判断购物车全部商品全选
  allischecked(mchlist, cart_list) {
    var mchcheck = true,
      check = true;
    if (cart_list.length == 0) {
      check = false;
    } else {
      for (var j = 0; j < cart_list.length; j++) {
        if (cart_list[j].is_checked == false) {
          check = false;
          break;
        }
      }
    }
    if (mchlist.length == 0) {
      mchcheck = false;
    } else {
      for (var i = 0; i < mchlist.length; i++) {
        for (var j = 0; j < mchlist[i].list.length; j++) {
          if (mchlist[i].list[j].is_checked == false) {
            mchcheck = false;
            break;
          }
        }
        if (mchcheck == false) {
          break;
        }
      }
    }
    if (mchlist.length == 0 || cart_list.length == 0) {
      if (mchlist.length == 0) {
        return check;
      }
      if (cart_list.length == 0) {
        return mchcheck;
      }
    }
    if (mchlist.length != 0 && cart_list.length != 0) {
      if (check == true && mchcheck == true) {
        return true;
      } else {
        return false;
      }
    }
  },
  //返回
  goBack(num = 1) {
    let pages = getCurrentPages();
    if (pages.length > num) {
      // #ifndef MP-TOUTIAO
      uni.navigateBack({
        delta: num
      });
      // #endif
      // #ifdef MP-TOUTIAO
      uni.redirectTo({
        url: "/pages/home/home"
      });
      // #endif
    } else {
      uni.switchTab({
        url: "/pages/home/home"
      });
    }
  },
  //提示消息
  toast(text, icon = "none", time = 2000) {
    uni.showToast({
      title: text,
      icon,
      duration: time
    });
  },
  trimString(value) {
    return value ? value.toString().replace(/(^\s*)|(\s*$)/g, "") : value;
  },
  px2upx(value) {
    let upx = 750;
    let px = uni.upx2px(750);
    return (value * upx) / px;
  },
  //字符串是否为空
  isTextEmpty(value) {
    return value == "" || value == null || typeof value === "undefined";
  },
  trim: function (value) {
    //去空格
    return value.replace(/(^\s*)|(\s*$)/g, "");
  },
  isMobile: function (value) {
    //是否为手机号
    return /^(?:13\d|14\d|15\d|16\d|17\d|18\d|19\d)\d{5}(\d{3}|\*{3})$/.test(
      value
    );
  },
  isFloat: function (value) {
    //金额，只允许保留两位小数
    return /^([0-9]*[.]?[0-9])[0-9]{0,1}$/.test(value);
  },
  isNum: function (value) {
    //是否全为数字
    return /^[0-9]+$/.test(value);
  },
  numToZh(num) {
    let result = num.toString();
    result = result.replace("0", "零");
    result = result.replace("1", "一");
    result = result.replace("2", "二");
    result = result.replace("3", "三");
    result = result.replace("4", "四");
    result = result.replace("5", "五");
    result = result.replace("6", "六");
    result = result.replace("7", "七");
    result = result.replace("8", "八");
    result = result.replace("9", "九");
    return result;
  },
  isLogin(isToLogin = true) {
    if (uni.getStorageSync("userInfo")) {
      return true;
    } else {
      //去登录页面
      if (isToLogin) {
        const routes = getCurrentPages();
        const route = routes[routes.length - 1].route;
        const param = routes[routes.length - 1].options;
        const params = uni.$u.queryParams(param);
        
        store.commit("setNoLoginTabarPath",`/${route + params}`);
        store.commit("setRouteType", "redirectTo");
        uni.removeStorageSync("hasUri");
        this.toUrl("/login/login/login_page", "redirectTo");
      }
      return false;
    }
  },
  checkPwd: function (value) {
    //密码为8~20位数字和字母组合
    return /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$/.test(value);
  },
  formatNum: function (num) {
    //格式化手机号码
    if (utils.isMobile(num)) {
      num = num.replace(/^(\d{3})\d{4}(\d{4})$/, "$1****$2");
    }
    return num;
  },
  rmoney: function (money) {
    //金额格式化
    return parseFloat(money)
      .toFixed(2)
      .toString()
      .split("")
      .reverse()
      .join("")
      .replace(/(\d{3})/g, "$1,")
      .replace(/\,$/, "")
      .split("")
      .reverse()
      .join("");
  },
  //显示超出长度的字符串后加。。。
  overhideText(value, length) {
    if (value.length > length) {
      return value.substring(0, length) + "...";
    } else {
      return value;
    }
  },
  //保存图片
  saveImg(url) {
    uni.saveImageToPhotosAlbum({
      filePath: url,
      success: () => {
        uni.hideLoading();
        uni.showToast({
          title: "图片保存成功～"
        });
      },
      fail: (err) => {
        uni.hideLoading();
        this.toast("图片保存失败！");
        if (
          err.errMsg == "saveImageToPhotosAlbum:fail:auth denied" ||
          err.errMsg == "saveImageToPhotosAlbum:fail auth deny"
        ) {
          uni.showModal({
            title: "提示",
            content: "需要您授权保存相册",
            showCancel: false,
            success: (modalSuccess) => {
              uni.openSetting({
                success(settingdata) {
                  if (settingdata.authSetting["scope.writePhotosAlbum"]) {
                    uni.showModal({
                      title: "提示",
                      content: "获取权限成功,再次点击图片即可保存",
                      showCancel: false
                    });
                  } else {
                    uni.showModal({
                      title: "提示",
                      content: "获取权限失败，将无法保存到相册哦~",
                      showCancel: false
                    });
                  }
                },
                fail(failData) {},
                complete(finishData) {}
              });
            }
          });
        }
      }
    });
  },
  //获取当前日期-分隔
  getNowFormatDate() {
    var date = new Date();
    var seperator1 = "-";
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
      month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
      strDate = "0" + strDate;
    }
    // var currentdate = year + seperator1 + month + seperator1 + strDate;
    var currentdate = year + seperator1 + month;
    return currentdate;
  },

  /**
   * 获取上一个月
   * @date 格式为yyyy-mm-dd的日期，如：2019-01-25
   * 对日期做处理，获取2019-03-28，29，30，31，都会返回2019-02-28
   *
   */
  getPreMonth(date) {
    var arr = date.split("-");
    var year = arr[0]; //获取当前日期的年份
    var month = arr[1]; //获取当前日期的月份
    var day = arr[2]; //获取当前日期的日
    var month2 = parseInt(month) - 1;
    if (month2 == 0) {
      year = parseInt(year) - 1;
      month2 = 12;
    }
    var days2 = new Date(year, month2, 0);
    days2 = days2.getDate();
    if (day > days2) {
      day = days2;
    }
    if (month2 < 10) {
      month2 = "0" + month2;
    }
    // var t2 = year + '-' + month2 + '-' + day;
    var t2 = year + "-" + month2;
    return t2;
  },
  /**
   * 获取下一个月-第二种
   * @date 格式为yyyy-mm-dd的日期，如：2019-01-25
   *
   */
  getNextMonth(date) {
    var arr = date.split("-");
    var year = arr[0]; //获取当前日期的年份
    var month = arr[1]; //获取当前日期的月份
    var day = arr[2]; //获取当前日期的日
    var month2 = parseInt(month) + 1;
    if (month2 == 13) {
      year = parseInt(year) + 1;
      month2 = 1;
    }
    var day2 = day;
    var days2 = new Date(year, month2, 0);
    days2 = days2.getDate();
    if (day2 > days2) {
      day2 = days2;
    }
    if (month2 < 10) {
      month2 = "0" + month2;
    }
    // var t2 = year + '-' + month2 + '-' + day2;
    var t2 = year + "-" + month2;
    return t2;
  },
  // 自定义跳转
  diySkip(param) {
    if (!param || param == "") {
      return;
    }
    const { link, open_type } = param || {};
    this.toUrl(link, open_type);
  },
  // 倒计时
  GetRTime(EndTime) {
    var EndTime = EndTime; //结束时间
    var NowTime = new Date(); //当前时间
    if (EndTime <= NowTime.getTime() / 1000) {
      return false;
    }
    //后台给我的是10位 精确到秒的  所有下面我就除以了1000，不要小数点后面的
    var t = EndTime - (NowTime.getTime() / 1000).toFixed(0);
    //如果后台给的是毫秒 上面不用除以1000  下面的计算时间也都要除以1000 这里我去掉1000了
    var d = Math.floor(t / 60 / 60 / 24); //天 var d=Math.floor(t/1000/60/60/24)
    var h = Math.floor((t / 60 / 60) % 24); //时 var h=Math.floor(t/1000/60/60%24)
    var m = Math.floor((t / 60) % 60); //分 var m=Math.floor(t/1000/60%60)
    var s = Math.floor(t % 60); //秒 var s=Math.floor(t/1000%60)
    if (parseInt(d) < 10) {
      d = "0" + d;
    }
    if (parseInt(h) < 10) {
      h = "0" + h;
    }
    if (parseInt(m) < 10) {
      m = "0" + m;
    }
    if (parseInt(s) < 10) {
      s = "0" + s;
    }
    return `${d}天${h}小时${m}分${s}秒`;
  },

  /**
   * 时间戳转为多久之前
   * @param String timestamp 时间戳
   **/
  timeFrom(dateTime = null) {
    // 如果为null,则格式化当前时间
    if (!dateTime) dateTime = Number(new Date());
    // 如果dateTime长度为10或者13，则为秒和毫秒的时间戳，如果超过13位，则为其他的时间格式
    if (dateTime.toString().length == 10) dateTime *= 1000;
    let timestamp = +new Date(Number(dateTime));

    let timer = (Number(new Date()) - timestamp) / 1000;
    // 如果小于5分钟,则返回"刚刚",其他以此类推
    let tips = "";
    switch (true) {
      case timer < 300:
        tips = "刚刚";
        break;
      case timer >= 300 && timer < 3600:
        tips = parseInt(timer / 60) + "分钟前";
        break;
      case timer >= 3600 && timer < 86400:
        tips = parseInt(timer / 3600) + "小时前";
        break;
      case timer >= 86400 && timer < 2592000:
        tips = parseInt(timer / 86400) + "天前";
        break;
      default:
        if (timer >= 2592000 && timer < 365 * 86400) {
          tips = parseInt(timer / (86400 * 30)) + "个月前";
        } else {
          tips = parseInt(timer / (86400 * 365)) + "年前";
        }
    }
    return tips;
  },
  //判断页面是否使用底部导航
  useFoot(controls, id) {
    let index = controls.findIndex((item) => {
      return item.show_type == "nav";
    });
    if (index != -1) {
      let routes = getCurrentPages();
      let curRoute = routes[routes.length - 1].route;
      let foot = controls[index];

      let pageIndex = foot.params.navList.findIndex((item) => {
        return item.link.link.indexOf(curRoute) != -1;
      });
      if (pageIndex == -1) {
        return false;
      }
      let pageLink = foot.params.navList[pageIndex].link;
      if (pageLink && pageLink != "") {
        if (curRoute == "pages/diy/diy") {
          let params = this.oneValues(pageLink.link);
          if (params.id == id) {
            return true;
          } else {
            return false;
          }
        } else {
          if (pageIndex > -1) {
            return true;
          } else {
            return false;
          }
        }
      }
    } else {
      return false;
    }
  },
  // 获取链接参数
  oneValues(url) {
    var name, value;
    var str = url; //取得整个地址栏
    var num = str.indexOf("?");
    str = str.substr(num + 1); //取得所有参数   stringvar.substr(start [, length ]
    let obj = {};
    var arr = str.split("&"); //各个参数放到数组里
    for (var i = 0; i < arr.length; i++) {
      num = arr[i].indexOf("=");
      if (num > 0) {
        name = arr[i].substring(0, num);
        value = arr[i].substr(num + 1);
        obj[name] = value;
      }
    }
    return obj;
  },
  // 解析小程序码scene
  sceneDecode(scene) {
    const sceneStr = decodeURIComponent(scene);
    let e = sceneStr.split(","),
      r = {};
    for (var n in e) {
      var a = e[n].split(":");
      0 < a.length && a[0] && (r[a[0]] = a[1] || null);
    }
    return r;
  },
  // 格式化专题内容
  formatRichText(html) {
    let newContent = html.replace(/<img[^>]*>/gi, function (match, capture) {
      match = match
        .replace(/style="[^"]+"/gi, "")
        .replace(/style='[^']+'/gi, "");
      match = match
        .replace(/width="[^"]+"/gi, "")
        .replace(/width='[^']+'/gi, "");
      match = match
        .replace(/height="[^"]+"/gi, "")
        .replace(/height='[^']+'/gi, "");
      return match;
    });
    newContent = newContent.replace(
      /style="[^"]+"/gi,
      function (match, capture) {
        match = match
          .replace(/width:[^;]+;/gi, "max-width:100%;")
          .replace(/width:[^;]+;/gi, "max-width:100%;");
        return match;
      }
    );
    newContent = newContent.replace(/<br[^>]*\/>/gi, "");
    newContent = newContent.replace(
      /\<img/gi,
      '<img style="max-width:100%;height:auto;display:inline-block;margin:10rpx auto;"'
    );
    return newContent;
  },
  // 节流
  throttle(fn, time) {
    let cd = true;
    return function (...args) {
      if (!cd) return;
      fn(this, ...args);
      cd = false;
      setTimeout(() => {
        cd = true;
      }, time);
    };
  },
  // 防抖
  debounce(fn, time) {
    let timer = null;
    return function (...args) {
      if (timer) {
        // 每次进来先结束计时
        clearTimeout(timer);
      }
      timer = setTimeout(() => {
        fn(this, ...args);
      }, time);
    };
  },
  // 检查wx.login获取的code是否过期
  checkWxSession() {
    // const code = uni.getStorageSync("wx_login_code");
    // if (!code) {
    uni.login({
      provider: "weixin",
      success: (res) => {
        uni.setStorageSync("wx_login_code", res.code);
      },
      fail: () => {}
    });
    // } else {
    //   uni.checkSession({
    //     success() {
    //       // 未过期，不做处理
    //     },
    //     fail() {
    //       uni.login({
    //         provider: "weixin",
    //         success: (res) => {
    //           uni.setStorageSync("wx_login_code", res.code);
    //         },
    //         fail: () => {},
    //       });
    //     },
    //   });
    // }
  },

  // 设置本地缓存数据
  setStorage(key, val) {
    try {
      uni.setStorageSync(key, val);
    } catch (e) {
      // error
    }
  },

  // 读取本地缓存数据
  getStorage(key) {
    if (!key || key.constructor != String) return;
    try {
      const value = uni.getStorageSync(key);
      if (value) {
        return value;
      } else {
        return null;
      }
    } catch (e) {
      // error
      return null;
    }
  },

  // 删除某个本地缓存数据
  removeStorage(key) {
    if (!key || key.constructor != String) return;
    try {
      uni.removeStorageSync(key);
    } catch (e) {
      // error
    }
  },

  // 清除本地缓存数据
  clearStorage() {
    try {
      uni.clearStorageSync();
    } catch (e) {
      // error
    }
  },

  // 时间戳毫秒转日期
  turnDate(time, type) {
    let date = new Date(time);
    let y = date.getFullYear();
    let m = date.getMonth() + 1;
    m = m < 10 ? "0" + m : m;
    let d = date.getDate();
    d = d < 10 ? "0" + d : d;
    let h = date.getHours();
    h = h < 10 ? "0" + h : h;

    let f = date.getMinutes();
    f = f < 10 ? "0" + f : f;

    let s = date.getSeconds();
    s = s < 10 ? "0" + s : s;

    return type === "yyyy-mm-dd"
      ? `${y}-${m}-${d}`
      : `${y}-${m}-${d} ${h}:${f}:${s}`;
  },

  // 删除左右两端的空格
  trim(str) {
    return str.replace(/(^\s*)|(\s*$)/g, "");
  },
  // 判断对象是否为空
  isEmpty(object) {
    for (var name in object) {
      return false;
    }
    return true;
  },
  // 对象去空
  objEmpty(object) {
    for (var i in object) {
      var value = object[i];
      const type = typeof value;
      // 去除空格
      if (type === "string") {
        object[i] = this.trim(value);
      }
      if (typeof value === "object") {
        // 是否引用数据类型
        if (Array.isArray(value)) {
          if (value.length === 0) {
            delete object[i];
            continue;
          }
        }
        this.objEmpty(value);
        if (this.isEmpty(value)) {
          delete object[i];
        }
      } else {
        // 基本数据类型
        if (value === "" || value === null || value === undefined) {
          delete object[i];
        }
      }
    }
    return object;
  },
  // 判断diy页面底部导航高亮
  diyPageFoot(current, link) {
    let index = current.indexOf("pages/diy/diy");
    if (index > -1) {
      if (current == link) {
        return true;
      } else {
        return false;
      }
    } else {
      return true;
    }
  },

  showModal(
    title = "提示",
    content = "",
    showCancel = true,
    confirm,
    cancel,
    confirmText = "确定",
    cancelText = "取消"
  ) {
    uni.showModal({
      title,
      content,
      showCancel,
      confirmText,
      cancelText,
      success(res) {
        if (res.confirm) {
          confirm();
        } else if (res.cancel) {
          cancel();
        }
      }
    });
  },

  /**
   * @function 数组平铺
   * @param data {Array}
   * @param key {String}
   * @param res {Array}
   * @return {Array}
   * */
  flatten(data, key, res = []) {
    data.forEach((item) => {
      let newItem = JSON.parse(JSON.stringify(item));
      delete newItem[key];

      res.push(newItem);
      if (item.children && item.children.length !== 0) {
        this.flatten(item.children, key, res);
      }
    });
    return res;
  },

  formatNumber(n) {
    n = n.toString();
    return n[1] ? n : "0" + n;
  },

  /**
   * @param {Date} date
   * @param {String} fmt yyyy-MM-dd hh:mm:ss
   * @returns
   */
  formatDate(date, fmt) {
    if (typeof date == "string") {
      return date;
    }

    if (!fmt) fmt = "yyyy-MM-dd hh:mm:ss";

    if (!date || date == null) return null;
    let o = {
      "M+": date.getMonth() + 1, // 月份
      "d+": date.getDate(), // 日
      "h+": date.getHours(), // 小时
      "m+": date.getMinutes(), // 分
      "s+": date.getSeconds(), // 秒
      "q+": Math.floor((date.getMonth() + 3) / 3), // 季度
      S: date.getMilliseconds() // 毫秒
    };
    if (/(y+)/.test(fmt))
      fmt = fmt.replace(
        RegExp.$1,
        (date.getFullYear() + "").substr(4 - RegExp.$1.length)
      );
    for (let k in o) {
      if (new RegExp("(" + k + ")").test(fmt))
        fmt = fmt.replace(
          RegExp.$1,
          RegExp.$1.length === 1
            ? o[k]
            : ("00" + o[k]).substr(("" + o[k]).length)
        );
    }
    return fmt;
  },

  // 金额处理
  priceFilter(price) {
    if (!price) return [0, ".00"];
    if (typeof price === "number") price = String(price);
    let arr = price.split(".");
    if (arr.length < 2) return [...arr, ".00"];
    return [arr[0], `.${arr[1]}`];
  },
  is_webpage() {
    /* #ifndef H5 */
    return false;
    /* #endif */
    let ua = window.navigator.userAgent.toLowerCase();
    return ua.match(/MicroMessenger/i) == "micromessenger";
  },
  // 是否微信浏览器
  isWechat() {
    // #ifdef H5
    var ua = navigator.userAgent.toLowerCase();
    if (ua.match(/micromessenger/i) == "micromessenger") {
      return true;
    } else {
      return false;
    }
    // #endif
    return false;
  },
  hideShareMenu() {
    // #ifdef MP-ALIPAY || MP-WEIXIN
    uni.hideShareMenu();
    // #endif
  },

  /*
   * 版本号比较方法
   * 传入两个字符串，当前版本号：curV；比较版本号：reqV
   * 调用方法举例：compare("1.1","1.2")，将返回false
   */
  compare(curV, reqV) {
    if (curV && reqV) {
      //将两个版本号拆成数字
      var arr1 = curV.split("."),
        arr2 = reqV.split(".");
      var minLength = Math.min(arr1.length, arr2.length),
        position = 0,
        diff = 0;
      //依次比较版本号每一位大小，当对比得出结果后跳出循环（后文有简单介绍）
      while (
        position < minLength &&
        (diff = parseInt(arr1[position]) - parseInt(arr2[position])) == 0
      ) {
        position++;
      }
      diff = diff != 0 ? diff : arr1.length - arr2.length;
      //若curV大于reqV，则返回true
      return diff > 0;
    } else {
      //输入为空
      return false;
    }
  },

  /**
   * @保存WEB图片
   * @param {String} url
   */
  saveImgWeb(url) {
    // #ifdef WEB
    let oA = document.createElement("a");
    oA.download = "";
    oA.href = url;
    document.body.appendChild(oA);
    oA.click();
    oA.remove();
    // #endif
  },

  /**
   * @上传
   */
  uploadImage(
    count = 1,
    success = () => {},
    fail = () => {},
    sizeType = ["original", "compressed"],
    sourceType = ["album", "camera"]
  ) {
    if (
      (uni.getStorageSync("platform") || uni.getSystemInfoSync().platform) ==
      "android"
    ) {
      this.showModal(
        "提示",
        "是否允许系统打开您的手机相册？用于获取信息上传图片",
        true,
        () => {
          this.uploadImageSubmit(count, success, fail, sizeType, sourceType);
        },
        () => {}
      );
    } else {
      this.uploadImageSubmit(count, success, fail, sizeType, sourceType);
    }
  },

  /**
   * @上传确认
   */
  uploadImageSubmit(count, success, fail, sizeType, sourceType) {
    let max = count,
      num = 0;
    uni.chooseImage({
      count,
      sourceType,
      sizeType,
      success: (result) => {
        if (result.errMsg == "chooseImage:ok") {
          uni.showLoading({
            title: "请稍等"
          });

          var tempFilePaths = result.tempFilePaths;
          tempFilePaths.forEach((el) => {
            http.UPLOAD_IMAGE(el, (res) => {
              if (res.code == 0) {
                success(res.url);
                num += 1;

                uni.hideLoading();
              } else {
                uni.showToast({
                  title: res.msg,
                  icon: "none",
                  duration: 2000
                });
              }
            });
          });
        }
      },
      fail: (res) => {
        fail(res);
      }
    });
  },

  /**
   * @拨打电话
   */
  makePhoneCall(phoneNumber) {
    if (
      (uni.getStorageSync("platform") || uni.getSystemInfoSync().platform) ==
      "android"
    ) {
      this.showModal(
        "提示",
        "当前操作申请获取电话权限，用来拨打客服！",
        true,
        () => {
          uni.makePhoneCall({
            phoneNumber
          });
        },
        () => {}
      );
    } else {
      uni.makePhoneCall({
        phoneNumber
      });
    }
  },

  /**
   * @获取平铺后数组
   * @param list
   * @param key
   * @return Array
   */
  getFlatArray(list, key = "list") {
    let old = JSON.parse(JSON.stringify(list));
    let newList = [];

    function flat(list, key = "list") {
      if (list && Array.isArray(list)) {
        list.forEach((item) => {
          if (item[key]) {
            flat(item[key]);
            delete item[key];
          }

          newList.push(item);
        });
      }
    }

    flat(old, key);

    return newList;
  }
};
